<template>
  <el-container class="retail-page">
    <el-header>商品销售</el-header>
    <el-main>
      <!-- 输入顾客姓名 -->
      <el-form :model="customerForm" @submit.prevent="submitOrder">
        <el-form-item label="顾客姓名" prop="customerName">
          <el-input v-model="customerForm.customerName" placeholder="请输入顾客姓名" />
        </el-form-item>
      </el-form>

      <!-- 输入ISBN号 -->
      <el-form :model="isbnForm" @submit.prevent="addItemByCode">
        <el-form-item label="ISBN号/编码" prop="isbn">
          <el-input 
            v-model="isbnForm.isbn" 
            placeholder="请扫描或输入ISBN号/编码" 
            @keyup.enter="addItemByCode"
            clearable
          />
        </el-form-item>
        <el-button type="primary" @click="addItemByCode">添加到订单</el-button>
      </el-form>

      <!-- 显示订单中的商品列表 -->
      <el-table :data="orderItems" style="margin-top: 20px;">
        <el-table-column prop="title" label="商品名" />
        <el-table-column prop="discount" label="折扣">
          <template #default="{ row }">
            {{ (row.discount * 100).toFixed(0) }}%
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格">
          <template #default="{ row }">
            ￥{{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量">
          <template #default="{ row }">
            <el-input-number 
              v-model="row.quantity" 
              :min="1" 
              @change="updateItemTotal(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="total" label="小计">
          <template #default="{ row }">
            ￥{{ row.total }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button 
              type="danger" 
              size="small" 
              @click="removeItem(scope.$index)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 订单总金额和提交按钮 -->
      <div class="total">
        <h3>订单总金额：￥{{ totalAmount.toFixed(2) }}</h3>
        <el-button type="danger" @click="clearOrder">清空订单</el-button>
        <el-button 
          type="success" 
          @click="submitOrder" 
          :disabled="orderItems.length === 0"
        >
          提交订单
        </el-button>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import BookService from '@/api/bookService';
import GoodsService from '@/api/goodsService';
import OrderService from '@/api/orderService';
import { ElMessage } from 'element-plus';

const isbnForm = reactive({
  isbn: ''
});

const customerForm = reactive({
  customerName: '散客'
});

const orderItems = ref([]);
const totalAmount = computed(() => {
  return orderItems.value.reduce((sum, item) => sum + parseFloat(item.total), 0);
});

async function addItemByCode() {
  if (!isbnForm.isbn) return;

  try {
    let foundItem = null;

    // 首先尝试在图书数据中查找
    try {
      const response = await BookService.getBookByISBN(isbnForm.isbn);
      foundItem = response.data;
      foundItem.type = 'book';
    } catch (bookError) {
      // 如果图书数据中没有找到，尝试在商品数据中查找
      try {
        const response = await GoodsService.getGoodsByCode(isbnForm.isbn);
        foundItem = response.data;
        foundItem.type = 'goods';
      } catch (goodsError) {
        console.error("未找到商品信息: ", goodsError);
        ElMessage.error("未找到图书或商品信息，请检查ISBN号或编码是否正确。");
        return;
      }
    }

    if (foundItem) {
      const existingItem = orderItems.value.find(item => 
        (foundItem.isbn && item.isbn === foundItem.isbn) || 
        (foundItem.code && item.code === foundItem.code)
      );
      
      if (existingItem) {
        existingItem.quantity += 1;
        updateItemTotal(existingItem);
      } else {
        const newItem = {
          title: foundItem.title || foundItem.name,
          discount: foundItem.sales_discount || 1,
          price: foundItem.price || foundItem.sale_price,
          isbn: foundItem.isbn,
          code: foundItem.code,
          quantity: 1,
          type: foundItem.type
        };
        updateItemTotal(newItem);
        orderItems.value.push(newItem);
      }
    }

    isbnForm.isbn = '';
  } catch (error) {
    console.error("Error fetching item by ISBN/Code: ", error);
    ElMessage.error("查询商品时出错，请稍后再试。");
  }
}

function updateItemTotal(item) {
  item.total = (item.quantity * item.price * item.discount).toFixed(2);
}

function removeItem(index) {
  orderItems.value.splice(index, 1);
}

function clearOrder() {
  orderItems.value = [];
  customerForm.customerName = '散客';
}

async function submitOrder() {
  if (!customerForm.customerName) {
    ElMessage.warning("请填写顾客姓名");
    return;
  }

  const orderData = {
    customer_name: customerForm.customerName,
    total_amount: totalAmount.value,
    items: orderItems.value.map(item => ({
      type: item.type,
      item_id: item.isbn || item.code,
      quantity: item.quantity,
      price: item.price,
      discount: item.discount
    }))
  };

  try {
    await OrderService.createOrder(orderData);
    ElMessage.success("订单提交成功");
    clearOrder();
  } catch (error) {
    console.error("Error submitting order: ", error);
    ElMessage.error("订单提交失败");
  }
}
</script>

<style scoped>
.retail-page {
  padding: 20px;
}

.el-header {
  background-color: #409EFF;
  color: white;
  text-align: center;
  padding: 10px;
  font-size: 24px;
}

.total {
  margin-top: 20px;
  text-align: right;
}

.total h3 {
  display: inline-block;
  margin-right: 20px;
}

.el-main {
  background-color: #fff;
  padding: 20px;
}
</style>
